$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/course/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true },
			{ label: '课程标题', name: 'title', index: 'title', width: 80 }, 			
			// { label: '课程图片', name: 'img', index: 'img', width: 80 },
            { label: '课程图片', name: 'img', index: 'img', width: 80 , formatter:function(value, options, row) {
                    return '<img  style="width: 50px" src="' + value + '">';
                }},
            { label: '课次', name: 'classtimeids', index: 'classtimeids', width: 65,formatter: function(cellvalue, options, rowdata) {
                    var name = "" ;
                    $.ajax({
                        type: "POST",
                        async:false,
                        url: baseURL + "sys/classtime/infoName/"+rowdata.classtimeids,

                        success: function(r){
                            if (null == r.name) {
                                name="";
                            } else {
                                name = r.name;
                            }
                        }
                    });
                    return name;
                }
            },
			{ label: '开课时间', name: 'classtime', index: 'classtime', width: 80 }, 			
			{ label: '添加时间', name: 'createtime', index: 'createtime', width: 80 }			
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});
layui.use('upload', function(){
    var upload = layui.upload;
});
layui.use('element', function(){
    var element = layui.element;
});
var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		course: {},
        classtime:[]
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.course = {};

            $("#xzImg").show()
            var upload = layui.upload; //得到 upload 对象
            console.log(upload);
            upload.render({
                elem: '#xzImg'
                ,url: baseURL + 'sys/course/upload/'
                ,auto: false //选择文件后不自动上传
                ,field : 'file'
                ,bindAction: '#isImg' //指向一个按钮触发上传
                ,choose: function(obj){
                    var files = obj.pushFile();
                    obj.preview(function(index, file, result){
                        $("#xsImg").html('<img src="'+ result +'" width="500px"   alt="'+ file.name +'">')
                    });
                }
                ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                    layer.load(); //上传loading
                }
                ,done: function(res, index, upload){ //上传后的回调
                    if(res.code==0){
                        layer.closeAll()
                        layer.msg("上传成功")
                        $("#img").val(res.fileName);
                    }
                }
            })

		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";

            $("#xzImg").show()
            var upload = layui.upload; //得到 upload 对象
            console.log(upload);
            upload.render({
                elem: '#xzImg'
                ,url: baseURL + 'sys/course/upload/'
                ,auto: false //选择文件后不自动上传
                ,field : 'file'
                ,bindAction: '#isImg' //指向一个按钮触发上传
                ,choose: function(obj){
                    var files = obj.pushFile();
                    obj.preview(function(index, file, result){
                        $("#xsImg").html('<img src="'+ result +'" width="500px"   alt="'+ file.name +'">')
                    });
                }
                ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                    layer.load(); //上传loading
                }
                ,done: function(res, index, upload){ //上传后的回调
                    if(res.code==0){
                        layer.closeAll()
                        layer.msg("上传成功")
                        $("#img").val(res.fileName);
                    }
                }
            })

            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                vm.course.img = $("#img").val();
                vm.course.classtime = $("#classtime").val()
                vm.course.explains = tinyMCE.activeEditor.getContent() ;
                var url = vm.course.id == null ? "sys/course/save" : "sys/course/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.course),
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "sys/course/delete",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
        addClasstime: function () {
            $("#jqGridAdd").jqGrid({
                url: baseURL + 'sys/classtime/list',
                datatype: "json",
                colModel: [
                    { label: 'id', name: 'id', index: 'id', width: 80, key: true },
                    { label: '课次名称', name: 'name', index: 'name', width: 100 },
                    { label: '题目', name: 'questionids', index: 'questionids', width: 270,formatter: function(cellvalue, options, rowdata) {
                            var img = '';
                            if(rowdata.questionids!=null&&rowdata.questionids!=''){
                                $.ajax({
                                    type: "POST",
                                    async:false,
                                    url: baseURL + "sys/question/infoName/"+rowdata.questionids,

                                    success: function(r){

                                        if(r.data!=null){
                                            var array = r.data.split(",");
                                            for(var i=0;i<array.length;i++){
                                                img += '<img  style="width: 50px" src="' + array[i] + '">';
                                            }

                                        }


                                    }
                                });
                            }

                            return img;
                        } },
                    { label: '添加时间', name: 'createtime', index: 'createtime', width: 150 }
                ],
                viewrecords: true,
                height: 385,
                rowNum: 10,
                rowList : [10,30,50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth:true,
                multiselect: true,
                pager: "#jqGridPager1",
                jsonReader : {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames : {
                    page:"page",
                    rows:"limit",
                    order: "order"
                },
                gridComplete:function(){
                    //隐藏grid底部滚动条
                    $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                }
            });
            $('#myModal').modal();
        },
        addClass: function (event) {
            var grid = $("#jqGridAdd");
            var rowKey = grid.getGridParam("selrow");
            if(!rowKey){
                alert("请选择一条记录");
                return ;
            }
            var rows = grid.getGridParam("selarrrow");

            var temp = "";
            $("#classtimeids").html("");
            for(var i=0;i<rows.length;i++){
                var obj = {};
                var isExits = false;
                if(vm.classtime.length>0){
                    for(var j=0;j<vm.classtime.length;j++){
                        if(rows[i]==vm.classtime[j].id){
                            isExits = true;
                        }
                    }
                    if(!isExits){
                        obj.id = rows[i];
                        obj.name = grid.getRowData(rows[i]).name;
                        vm.classtime.push(obj);

                    }

                }else{
                    obj.id = rows[i];
                    obj.name = grid.getRowData(rows[i]).name;
                    vm.classtime.push(obj);


                }

            }
            for(var k=0;k<vm.classtime.length;k++){
                temp +="<a class='btn' style='color: #333;border-color: #ccc;cursor:default;' " +
                    "id='"+vm.classtime[k].id+"'>"+vm.classtime[k].name+"</a>" +
                    "<img src='../../statics/img/ico15-close.png' onclick='vm.removeClassTimes("+vm.classtime[k].id+")'" +
                    "style='z-index:12;width:13px;height:13px;margin-left:-14px;margin-top:-15px;cursor: pointer; ' />&nbsp;&nbsp;";
            }
            vm.course.classtimeids='';
            for(var j=0;j<vm.classtime.length;j++){
                vm.course.classtimeids+=vm.classtime[j].id+","
            }
            str = vm.course.classtimeids.substring(0, vm.course.classtimeids.lastIndexOf(','));
            vm.course.classtimeids = str;
            $("#classtimeids").append(temp);
            console.log(temp)
            console.log(vm.classtime)
            $('#myModal').modal("hide");
        },
        removeClassTimes: function (id) {
            var temp = "";
            if(vm.classtime.length==1){
                alert("至少选择一个课次");
                return;
            }
            $("#classtimeids").html("");
            var classtimetemp = [];
            for(var i=0;i<vm.classtime.length;i++){
                var obj = {};

                if(vm.classtime[i].id !=id){
                    obj.id = vm.classtime[i].id;
                    obj.name = vm.classtime[i].name
                    classtimetemp.push(obj);

                    temp +="<a class='btn' style='color: #333;border-color: #ccc;cursor:default;' " +
                        "id='"+vm.classtime[i].id+"'>"+vm.classtime[i].name+"</a>" +
                        "<img src='../../statics/img/ico15-close.png' onclick='vm.removeClassTimes("+vm.classtime[i].id+")'" +
                        "style='z-index:12;width:13px;height:13px;margin-left:-14px;margin-top:-15px;cursor: pointer; ' />&nbsp;&nbsp;";
                }

            }
            vm.classtime = classtimetemp;
            $("#classtimeids").append(temp);
        },
		getInfo: function(id){
			$.get(baseURL + "sys/course/info/"+id, function(r){
                vm.course = r.course;
                tinyMCE.activeEditor.setContent(r.course.explains)
                $.get(baseURL + "sys/classtime/infoName/"+vm.course.classtimeids, function(r) {
                    $("#kcid").val(r.name);

                })
            });
		},
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		}
	}
});